package com.wjw.leetcode;

import com.wjw.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * intersection-of-two-linked-lists
 * 相交链表
 */
public class leetcode160 {

    // 借用缓存
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;

        Set<ListNode> set = new HashSet<ListNode>();
        ListNode curr = headA;
        while (curr != null) {
            set.add(curr);
            curr = curr.next;
        }

        curr = headB;
        while (curr != null) {
            if (set.contains(curr)) return curr;
            curr = curr.next;
        }
        return null;
    }

    // 双指针法
    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;

        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
